import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;



public class TcpEchoSever {
    private ServerSocket serverSocket = null;
    public TcpEchoSever (int port) throws IOException {
        serverSocket  = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //建立多个线程以防一个线程阻塞后后续客户端无法与服务器连接
            Socket socket = serverSocket.accept();
            Thread t = new Thread(()-> {
                try {
                    processonConnection(socket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }
    }

    private void processonConnection(Socket clientSocket) throws IOException {
        System.out.println("客户端上线" + clientSocket.getInetAddress());
        //1 接受客户端数据
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            while(true) {
                Scanner sc = new Scanner(inputStream);
                if (!sc.hasNext()) {
                    System.out.println("客户端下线" + clientSocket.getInetAddress());
                    break;
                }
                //字节流接受文件较为灵活，在这里指定空白符为分割
                //在传输文件时也要注意这一点
                String request = sc.next();
                //2 计算响应
                String respond = process(request);
                //将响应发送回客户端，把outputStream用PrintWriter包裹起来
                PrintWriter printWriter = new PrintWriter(outputStream);
                //这里并不是写到控制台，而是写到客户端
                printWriter.println(respond);
                //以防数据覆盖，将客户端冲刷
                printWriter.flush();
                //这里又少一个参数 自己补充下
                System.out.printf("[%s] req:%s,resp:%s\n",
                        clientSocket.getInetAddress(), request, respond);
            }
        }catch(IOException e){
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }
    }


    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoSever tcpEchoSever = new TcpEchoSever(9991);
        tcpEchoSever.start();
    }
}
